extends /templates/core/modal-base-flat

include ../teachers/common/license-form-group-mixin
include ../teachers/common/license-type-mixin
include ./mixins/products-mixin

//- DNT

block modal-header-content

  .row
    .col-sm-6
      h4 Name: #{view.user.get('name')} (#{view.user.get('firstName')} #{view.user.get('lastName')})
      h4 Email: #{view.user.get('emailLower') || view.user.get('email')}
      h4
        span= 'ID: '
        code= view.user.get('_id')
      if view.user.isTeacher() && view.trialRequest
        - var props = view.trialRequest.get('properties') || {}
        h4 School: #{props.nces_school || props.organization}
        h4 District: #{props.nces_district || props.district}
      if view.user.get('role')
        h4
          - var outcomesReportKind = view.user.isStudent() ? 'student' : view.user.isSchoolAdmin() ? 'school-admin' : 'teacher'
          a(href='/outcomes-report/' + outcomesReportKind + '/' + view.user.get('_id') data-i18n="outcomes.view_outcomes_report")

    .col-sm-3
      if me.isAdmin()
        button#user-spy-btn.btn.btn-primary.btn-block Spy
      if view.user.isStudent() && me.isAdmin()
        button#destudent-btn.btn.btn-burgundy.btn-block Destudent
      if view.user.isTeacher() && me.isAdmin()
        button#deteacher-btn.btn.btn-burgundy.btn-block Deteacher
      if !view.user.isTeacher() && me.isAdmin()
        button#reset-progress-btn.btn.btn-burgundy.btn-block Reset Progress
      if me.isAdmin()
        a#export-data-btn.btn.btn-primary.btn-block(target='_blank' href='/db/user/' + view.user.id + '/export-data') Export GDPR User Data

    .col-sm-3
      if view.prepaids.size()
        div
          a.modal-nav-link(href="#prepaids") Existing Prepaids
      if view.user.isTeacher()
        div
          a.modal-nav-link(href="#licenses") Grant Student Licenses
      if view.classrooms.size()
        div
          a.modal-nav-link(href="#classrooms") Classrooms
      if view.user.isHomeUser()
        div
          a.modal-nav-link(href="#stripe") Modify Subscription
      if me.isOnlineTeacher()
        div
          a.modal-nav-link(href="#other-controls") Other Controls
      // Not currently used
      //div
      //  a.modal-nav-link(href="#create-payment") Create Payment
      div
        a.modal-nav-link(href="#database-entries") Database Entries

  if view.user.isTeacher() && me.isAdmin()
    div.m-t-1
      // Not currently used
      //label
      //  input#verified-teacher-checkbox(type='checkbox', checked=view.userIsVerifiedTeacher())
      //  span.p-l-1
      //    | APCSP Verified Teacher (has access to private forum)
      //br
      label
        input#school-admin-checkbox(type='checkbox', checked=view.userIsSchoolAdmin())
        span.p-l-1
          | Enable School Administrator
        span.p-l-1
          a#edit-school-admins-link edit teachers
      div
        if view.userSaveState == 'saving'
          | Saving...
        else if view.userSaveState == 'saved'
          | Saved!

  if view.user.isHomeUser() && me.isAdmin()
    div.m-t-1
      label
        input#online-teacher-checkbox(type='checkbox', checked=view.userIsOnlineTeacher())
        span.p-l-1
          | Enable Online Teacher
      if view.userIsOnlineTeacher()
        span.p-l-1
          a#edit-online-teacher-link edit Info
      div
        if view.userSaveState == 'saving'
          | Saving...
        else if view.userSaveState == 'saved'
          | Saved!
      div.edit-online-teacher

  if view.user.isTeacher() && me.isAdmin()
    div.m-t-1
      label
        input#beta-tester-checkbox(type='checkbox', checked=view.userIsBetaTester())
        span.p-l-1
          | Enable Beta Tester
        span.small  (classroom Java/C++, blocks, Junior)
      div
        if view.userSaveState == 'saving'
          | Saving...
        else if view.userSaveState == 'saved'
          | Saved!

block modal-body-content
  if view.editingSchoolAdmins
    h3.m-t-3#school-admins-title Edit School Admin Teacher Access
    h5 Add teacher
    table.table.table-condensed
      .form-horizontal
        form#teacher-search-form.form-group
        .col-sm-4
          input.form-control#teacher-search(type="text")
        .col-sm-1
          button.btn.btn-primary.btn-large#teacher-search-button Search
        .col-sm-1
          button.btn.btn-large#clear-teacher-search-button Clear results
      #teacher-search-result
    if view.userSaveState
      br
      div= view.userSaveState
    br
    h5 Edit teachers
    br
    table.table.table-condensed
      #school-admin-result

  if view.editingOnlineTeacher
    .form#online-teacher-info
      - info = view.onlineTeacherInfo
      if info
        h3.m-t-3.online-teacher-title Edit Online Teacher's Info
        h6 Google Calendar Id
        span the email they share calendar to classes@codecombat.com
        .form-group.google-calendar-id
          - gmailInfo = info.googleCalendarId || ''
          label
            input(type='text' name='googleCalendarId' value=gmailInfo)
        h6 Spoken Languages
        .form-group.languages
          - languageInfo = info.languages || []
          each lang in view.onlineTeacherSchema.properties.languages.items.enum
            .checkbox
              label(class="languages-"+lang)
                input(type='checkbox' name="languages" value=lang checked=languageInfo.includes(lang))
                span= lang
        h6 Trials Only
        .form-group
          .checkbox
            label
              input(type='checkbox', name='trialsOnly' value='1' checked=info.trialsOnly)
              | Yes
        h5 Can Teach
        h6 Products
        .form-group.products
          - productInfo = info.products || []
          each product in view.onlineTeacherSchema.properties.products.items.enum
            .checkbox
              label(class="products-"+product)
                input(type='checkbox' name="products" value=product checked=productInfo.includes(product))
                span= product
        h6 Code Languages
        .form-group
          - codeLanguageInfo = info.codeLanguages || []
          each lang in view.onlineTeacherSchema.properties.codeLanguages.items.properties.language.enum
            span.codeLanguages= lang
            h7 - Levels:
            - langInfo = (codeLanguageInfo.filter(l => l.language === lang))[0] || {}
            - levelsInfo = langInfo.level || []
            each level, index in ['Beginners', 'Intermediate', 'Advanced']
              .checkbox
                label
                  input(type='checkbox' name=lang + ".level" value=index checked=levelsInfo.includes(index))
                  span= level
            br
        h6 Availability
        span note: default timezone is
        span=view.timeZone
        // todo: adding timezone switcher here
        .form-group
          - userTimeZone = view.userTimeZone
          if userTimeZone != view.timeZone
            +license-form-group('Use User TimeZone? (' + userTimeZone + ')')(type="checkbox" name="userTimeZone" value=false)
          - scheduleInfo = info.schedule || []
          each day in view.DAYS_OF_WEEK
            span.day= day
            h7 - Times:
            - dayInfo = (scheduleInfo.filter(s => s.day === day))[0] || {}
            - timeInfo = dayInfo.time || []
            input.day-time(type='text' name=day + '.time' placeholder="Input available start time(0-23), like 1,2,5,17-19" value=timeInfo.join(','))
            br
        .form-group
          button#save-online-teacher-info.btn.btn-primary Save

  if view.prepaids.size()
    h3.m-t-3#prepaids(data-toggle="collapse" data-target="#prepaids-table" aria-expanded="true" aria-controls="prepaids-table") Existing Prepaids
      span.small click to toggle collapse
    #prepaids-table.collapse.in.multi-collpase
      table.table.table-condensed
        tr
          th ID
          th Shared by
          th Type
          if view.timeZone == 'Asia/Shanghai'
            th Issued (CT)
            th Start (CT)
            th End (CT)
          else
            th Issued (PT)
            th Start (PT)
            th End (PT)
          th Used
          th Revokable
        for prepaid in view.prepaids.models
          - var prepaidControlId=prepaid.id
          tr(id=prepaidControlId)
            td= prepaid.id
            td
              if prepaid.creator
                if prepaid.creator.id !== view.user.id
                  a.user-link(data-user-id=prepaid.creator.id)
                    = prepaid.creator.get('name')
                else
                  | -
            td= prepaid.typeDescription()
            td= view.momentTimezone(new Date(parseInt(prepaid.id.substring(0, 8), 16) * 1000)).tz(view.timeZone).format('l')
            td
              if prepaid.get('startDate')
                if view.prepaidTableState && view.prepaidTableState[prepaid.id] === 'editMode'
                  - var startDateControlId='startDate-'+prepaid.id
                  input(id= startDateControlId type="date" name="startDate" value=view.momentTimezone(prepaid.get('startDate')).tz(view.timeZone).format('YYYY-MM-DD'))
                else
                  = view.momentTimezone(prepaid.get('startDate')).tz(view.timeZone).format('l')
            td
              if prepaid.get('endDate')
                if view.prepaidTableState && view.prepaidTableState[prepaid.id] === 'editMode'
                  - var endDateControlId='endDate-'+prepaid.id
                  input(id= endDateControlId type="date" name="endDate" value=view.momentTimezone(prepaid.get('endDate')).tz(view.timeZone).format('YYYY-MM-DD'))
                else
                  = view.momentTimezone(prepaid.get('endDate')).tz(view.timeZone).format('l')
            td
              if view.prepaidTableState && view.prepaidTableState[prepaid.id] === 'editMode'
                - var totalLicensesControlId='totalLicenses-'+prepaid.id
                = (prepaid.get('redeemers') || []).length + ' / '
                input(id=totalLicensesControlId type="number" name="totalLicenses" value=prepaid.get('maxRedeemers'), style="width:50px")
              else
                = (prepaid.get('redeemers') || []).length + ' / ' + prepaid.get('maxRedeemers') || 0
            td
              if view.prepaidTableState && view.prepaidTableState[prepaid.id] === 'editMode'
                - var revokableControlId='revokable-'+prepaid.id
                input(id=revokableControlId type="checkbox" name="revokable" checked=(!prepaid.get('irrevocable')), style="width:30px")
              else
                = (prepaid.get('irrevocable') ? 'No' : 'Yes')
            td
              if view.prepaidTableState && view.prepaidTableState[prepaid.id] === 'editMode'
                button.btn.btn-primary.save-prepaid-info-btn(data-prepaid-id=prepaid.id) Save
                button.btn.btn-primary.cancel-prepaid-info-edit-btn(data-prepaid-id=prepaid.id) Cancel
              else
                button.btn.btn-primary.edit-prepaids-info-btn(data-prepaid-id=prepaid.id) Edit
    hr

  h3.m-t-3#credits Add Extra Credits
  #credit-form.form

    if view.state === 'creating-credits'
      .progress.progress-striped.active
        .progress-bar(style="width: 100%")

    else if view.state === 'made-credits'
      h3 Credits created!
      .alert.alert-success Credits created!

    else
      div(style="display: flex; gap: 10px; align-items: flex-start")
        +license-form-group('Number of Credits')(id="credit-input" type="number", name="credits", min="1")
          h4.small(style="max-width: 700px") Credits end at 11:59pm PT of the end date selected
          +license-form-group('End Date')(type="date" name="endDate" value=view.momentTimezone().tz(view.timeZone).add(1, 'year').format('YYYY-MM-DD'))
        .form-group
          - creditType = view.creditType
          label
            span Credit Types
            =": "
            select#credit-type-select
              option(value='HACKSTACK_QUERY' selected=creditType==='HACKSTACK_QUERY') Hackstack
              option(value='LEVEL_CHAT_BOT' selected=creditType==='LEVEL_CHAT_BOT') Level Chat Bot
        .form-group
          button#add-credits-btn.btn.btn-primary Add Credits
    hr

  if view.user.isTeacher()
    h3.m-t-3#licenses Grant Student Licenses
    #prepaid-form.form
      if view.state === 'creating-prepaid'
        .progress.progress-striped.active
          .progress-bar(style="width: 100%")

      else if view.state === 'made-prepaid'
        .alert.alert-success Licenses created!

      else
        if view.timeZone == 'Asia/Shanghai'
          h4.small(style="max-width: 700px") Licenses start at 12am CT on the start date and end at 11:59pm CT on the end date listed.
        else
          h4.small(style="max-width: 700px") Licenses start at 12am PT on the start date and end at 11:59pm PT on the end date listed.
        +license-form-group('Number of Licenses')(id="seats-input" type="number", name="maxRedeemers", min="1")
        +license-type(view.licenseType, view.licensePresets, view.utils, view.creditDetails)
        +license-form-group('Start Date')(type="date" name="startDate" value=view.momentTimezone().tz(view.timeZone).format('YYYY-MM-DD'))
        +license-form-group('End Date')(type="date" name="endDate" value=view.momentTimezone().tz(view.timeZone).add(1, 'year').format('YYYY-MM-DD'))
        - userTimeZone = view.userTimeZone
        if userTimeZone != view.timeZone
          +license-form-group('Use User TimeZone? (' + userTimeZone + ')')(type="checkbox" name="userTimeZone" value=false)
        +license-form-group('Allow Revoke Licenses?')(type="checkbox" name="revokable" value=on checked)
        .form-group
          button#add-seats-btn.btn.btn-primary Add Licenses
      hr

  #call-sales-products
    if view.callSalesProducts.length
      +products-list(view.callSalesProducts, 'call-sales', [], view.productTableState)
    hr

  if view.user.isTeacher()
    include ./components/call-sales-product-creation
    hr

  #esports-products
    if view.esportsProducts.length
      -
        esportsKeys = {
          teams: {
            default: (options) => view.ESPORTS_PRODUCT_STATS.TEAMS[options.type.toUpperCase()],
            type: 'number',
            attributes: { min: view.ESPORTS_PRODUCT_STATS.TEAMS.MIN, max: view.ESPORTS_PRODUCT_STATS.TEAMS.MAX, step: 1}
           },
          tournaments: {
            default: (options) => view.ESPORTS_PRODUCT_STATS.TOURNAMENTS[options.type.toUpperCase()],
            extra: (product) => ((product.productOptions.createdTournaments || 0) + ' / '),
            type: 'number',
            attributes: { min: view.ESPORTS_PRODUCT_STATS.TOURNAMENTS.MIN, step: 1}
           },
          arena: {
            default: () => '',
            type: 'text',
            attributes: { placeholder: 'amdocs-quickfire-infinite-inferno,codestars-challenge' }
           },
        }
      +products-list(view.esportsProducts, 'esports', esportsKeys, view.productTableState)
      hr

  //- could be clan owner, but let's check teacher first
  if view.user.isTeacher() || view.user.isHomeUser()
    include ./components/esports-product-creation
    hr

  if view.classrooms.size()
    h3.m-t-3#classrooms(data-toggle="collapse" data-target="#classroom-table" aria-expanded="true" aria-controls="classroom-table") Classrooms
      span.small click to toggle collapse
    #classroom-table.collapse.in.multi-collapse
      table.table
        tr
          th Name
          th Lang
          th Students
          if view.user.isTeacher()
            th # Levels / Courses
            th
          else
            th Teacher
          th
        for classroom in view.classrooms.models
          tr
            td
              = classroom.get('name')
              if classroom.get('archived')
                i.spl.text-muted (archived)
            td= classroom.capitalLanguage
            td= (classroom.get('members') || []).length
            if view.user.isTeacher()
              td #{classroom.getLevels().size()} / #{(classroom.get('courses') || []).length}
              td
                button.btn.btn-primary.update-classroom-btn(data-classroom-id=classroom.id) Update All Levels
                button.btn.btn-primary.add-new-courses-btn(data-classroom-id=classroom.id) Add New Courses
            else
              td
                a.other-user-link(href='#' + classroom.get('ownerID') data-user-id=classroom.get('ownerID'))
                  if view.ownerNameMap && view.ownerNameMap[classroom.get('ownerID')]
                    span= view.ownerNameMap[classroom.get('ownerID')]
                  else
                    span= classroom.get('ownerID')
            td
              a(href='/teachers/classes/' + classroom.get('_id') + '#students-tab') View Class
    hr

  if view.user.isHomeUser()
    if me.isAdmin()
      h3.m-t-3#stripe Modify Subscription
      h4= 'Status: ' + (view.user.hasSubscription() ? 'subscribed' : 'not subscribed')
      .small Use this to grant premium access and gems to this user for the home version.
      .form
        .form-group
          .radio
            label
              input(type="radio" name="stripe-benefit" value="" checked=view.none)
              | None
          .radio
            label
              input(type="radio" name="stripe-benefit" value="free" checked=view.free)
              | Premium
          .radio
            label
              input(type="radio" name="stripe-benefit" value="free-until" checked=view.freeUntil)
              span Premium Until
              =" "
              input(type="date" name="stripe-free-until" value=view.freeUntilDate)#free-until-date
          .radio
            label
              input(type="radio" name="stripe-benefit" value="coupon" checked=view.coupon)
              span Coupon
              =" "
            select#coupon-select
              for coupon in view.coupons.models
                option(value=coupon.id selected=coupon.id===view.currentCouponID)= coupon.formatString()
        .form-group
          label
            span Gems to add to user
            =" "
            input#stripe-add-gems(type="number", name="addGems", value=0)
            |  (they have #{view.user.gems().toLocaleString()})
        button#save-changes.btn.btn-primary Save Changes
      hr
    else if me.isOnlineTeacher()
      h3.m-t-3#stripe Modify Subscription
      h4= 'Status: ' + (view.user.hasSubscription() ? 'subscribed' : 'not subscribed')
      .small Use this to grant premium access and gems to this user for the home version.
      .form
        .form-group
          .radio
            label
              input(type="radio" name="stripe-benefit" value="" checked=view.none)
              | None
          .radio
            label
              input(type="radio" name="stripe-benefit" value="free" checked=view.free)
              | Premium (use this for paid students)
          .radio
            label
              input(type="radio" name="stripe-benefit" value="free-until" checked=view.freeUntil)
              span Premium Until
              =" "
              input(type="date" name="stripe-free-until" value=view.freeUntilDate)#free-until-date
              |  (use this for trial class students)
        .form-group
          label
            span Gems to add to user
            =" "
            input#stripe-add-gems(type="number", name="addGems", value=0)
            |  (they have #{view.user.gems().toLocaleString()})
        button#save-changes.btn.btn-primary Save Changes
      hr

    if me.isOnlineTeacher()
      h3.m-t-3#other-controls Other Controls
      .small Currently only works when user is playing a level, takes effect when they finish the level.
      .form
        .form-group
          .checkbox
            label
              input#volume-checkbox(type='checkbox', checked=view.user.get('volume', true) > 0)
              span Volume
          .checkbox
            label
              input#music-checkbox(type='checkbox', checked=view.user.get('music', true))
              span Music
      hr

  else if view.user.isStudent() && (me.isAdmin() || me.isOnlineTeacher())
    h3.m-t-3#stripe Grant Gems
    .form
      .form-group
        label
          span Gems to add to user
          =" "
          input#stripe-add-gems(type="number", name="addGems", value=0)
          |  (they have #{view.user.gems().toLocaleString()})
      button#save-changes.btn.btn-primary Save Changes
    hr

  // Not currently used
  //h3#create-payment Create Payment
  //.small Use this to create a payment entry for this user.
  //.form
  //  .form-group
  //    pre
  //      table
  //        tr
  //          td purchaser:
  //          td= view.user.id
  //        tr
  //          td recipient:
  //          td= view.user.id
  //        tr
  //          td service:
  //          td
  //            input#payment-service(type='text', value='paypal')
  //            =" "
  //            span Only enter paypal, stripe, or external
  //        tr
  //          td gems:
  //          td
  //            input#payment-gems(type='number', value='10500')
  //        tr
  //          td amount:
  //          td
  //            input#payment-amount(type='number', value='2997')
  //        tr
  //          td description:
  //          td
  //            input#payment-description(type='text')
  //  button#create-payment-btn.btn.btn-primary Create Payment
  //hr

  h1#database-entries Database Entries
  for model in view.models
    .model-container(data-model-id=model.id)
      h3= model.type() + ': ' + model.id
      .model-treema(data-model-id=model.id)
      if me.isAdmin()
        btn.btn.btn-success.save-model(data-i18n="common.save") Save
    hr


block modal-footer
